/*
 * Copyright 2014 Will Dignazio
 */
#include <stdlib.h>
#include "internal.h"

/* Allocate room in the cache space for an object */
UCacheObj*
allocobj(u64 bufsz, UCache* uc)
{
	UCacheObj* uobj;
	void* buf;

	uobj = NULL;
	buf = NULL;

	if(uc->mem_alloced + bufsz > uc->mem_max)
		return CACHE_ENOMEM;

	/* Allocate the physical memory for the file */
	if(bufsz != 0) {
		buf = calloc(1, bufsz);
		if(buf == NULL)
			goto fail;
	}

	uobj = calloc(1, sizeof(UCacheObj));
	if(uobj == NULL)
		goto fail;

	uc->mem_alloced += bufsz;
	uobj->bufsz = bufsz;
	uobj->co_ref.vbuf = buf;
	uobj->type = UOBJ_FILE;

	return uobj;

fail:
	if(buf != NULL)
		free(buf);
	if(uobj != NULL)
		free(uobj);

	return NULL;
}
